var app = getApp();

Page({
  data: {
    classtab: [],
    res: [],
    indexId: 0,
    loadingTxt: '',
    loadingList: false,
    showGoTop: false,
    noMoreData: false,
    order: "",
    cid: "",
    page: 1,
    size: 16
  },

  orderProduct(e) {
    let status = this.data.order;
    let order = e.target.dataset.order;
    if (status == 'low_price' && order == 'low_price') {
      order = 'high_price';
    }

    this.setData({
      order: order,
      page:1
    })

    this.getPorducts();
  },

  productCid(e) {
    let cid = e.target.dataset.id;
    this.setData({
      cid: cid,
      page: 1,
      q: ''
    })
    this.getPorducts();
  },

  addCart: function (e) {
    let id = e.target.id;
    let img_url = e.target.dataset.img;
    let price = e.target.dataset.price;
    let old_price = e.target.dataset.oldprice;
    let name = e.target.dataset.name;
    let qty = 1;
    var that = this;
    console.log(wx.getStorageSync('token'))
    let token = wx.getStorageSync('token');
    if (token) {
      app.getUserToken(function (err, token) {
        wx.request({
          url: app.globalData.url +'/index.php?_m=checkout/cart/add_cart&v=v20190909b',
          data: { id: id, qty: qty, auth_token: token },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: (res) => {
            if (res.data.status == 401) {
              // 清空授权token
              app.globalData.token = null
              wx.removeStorageSync('token')
              that.addCart();
            } else if (res.data.code == 0) {
              wx.showToast({
                title: '加入购物车成功',
                icon: 'none',
                duration: 1500
              })
              setTimeout(function () {
                wx.hideToast()
              }, 1500)
            }
          }
        })
      })
    } else {
      var cartItems = wx.getStorageSync('cartItems') || []
      var exist = cartItems.find(function (ele) {
        return ele.id === id
      })

      if (exist) {
        //如果存在，则增加该货品的购买数量
        exist.qty = parseInt(exist.qty) + qty
      } else {
        //如果不存在，传入该货品信息
        cartItems.push({
          id: id,
          qty: qty,
          name: name,
          img_url: img_url,
          price: price,
          old_price: old_price
        })
      }
      wx.setStorage({
        key: 'cartItems',
        data: cartItems,
        success: function (res) {
          wx.showToast({
            title: '加入购物车成功',
            icon: 'none',
            duration: 1500
          })
          setTimeout(function () {
            wx.hideToast()
          }, 1500)
        }
      })

    }
  },

  getPorducts(options) {
    var that = this;
    var page = this.data.page;
    var size = this.data.size;
    var order = this.data.order;
    var cid = this.data.cid;
    var q = this.data.q;
  
    var regPos = /^\d+$/;

    let url = app.globalData.url +'/index.php?_m=shop/product/listing';

    if (order != '' && cid != '') {
      url = app.globalData.url +'/index.php?_m=shop/product/listing&order=' + order + '&cid=' + cid;
    } else if (order == '' && cid != '') {
      url = app.globalData.url +'/index.php?_m=shop/product/listing&cid=' + cid;
    } else if (order != '' && cid == '') {
      url = app.globalData.url +'/index.php?_m=shop/product/listing&order=' + order;
    }

    if (q) {
      if (order != '' && q != '') {
        url = app.globalData.url +'/index.php?_m=shop/product/listing&order=' + order + '&q[like-name]=' + q;
      } else if (order == '' && q != '') {
        url = app.globalData.url +'/index.php?_m=shop/product/listing&q[like-name]=' + q;
      }
    }

 
    wx.request({
      url: url,
      data: { size: size, page: page },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'get',
      success: (res) => {

        wx.setNavigationBarTitle({
          title:res.data.title
        })
        let goods = [];
        if (page == 1) {
          goods = res.data.data;
        } else {
          goods = that.data.res.concat(res.data.data);
        }

        that.setData({
          loadingList: true,
          loadingTxt: '加载中',
          noMoreData: false,
          res: goods
        });
      
        if (res.data.data.length < that.data.size) {
  
          that.setData({

            loadingTxt: '没有更多内容',

            noMoreData: true,

          });

        }

      }
    })

  },

  onLoad: function (options) {

    if (options.cid) {
      this.setData({
        cid: options.cid
      })
    }

    if (options.q) {
      this.setData({
        q: options.q
      })
    }
    this.getPorducts();
    this.getCategory();

  },

  getCategory(){
    wx.request({
      url: app.globalData.url +'/index.php?_m=shop/category/listing',
      data: {},
      success: (res) => {
        this.setData({
          classtab: res.data.data
        })
      }
    })
  },

  onPullDownRefresh: function () {
    wx.showToast({
      title: '加载中...',
      icon: 'loading'
    })

    this.getPorducts();

    setTimeout(function () {
      wx.stopPullDownRefresh()
    }, 1000)

  },

  onReachBottom: function () {
    if (!this.data.noMoreData) {
      this.data.page = this.data.page + 1;
      this.getPorducts();
    };

  },

  onPageScroll: function (e) {
    if (e.scrollTop > 200) {
      this.setData({
        showGoTop: true
      })
    } else {
      this.setData({
        showGoTop: false
      })
    }
  },
  // 回到顶部
  goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  onShareAppMessage: function () {
    app.globalData.uid = app.globalData.uid || wx.getStorageSync('uid') || 0;
    return {
      title: '深圳智汇创想科技有限责任公司员工福利购!',
      path: '/pages/index/index?fid=' + app.globalData.uid
    }
  }


})